import 'package:flutter/material.dart';
import 'package:class_teacher_student/extension/global_key_extension.dart';
import 'package:class_teacher_student/model/section.dart';




class StickyHead extends StatefulWidget {

  List<Section> sections;

  StickyHead(List<Section> this.sections, {Key key} ):super(key: key);

  @override
  StickyHeadState createState() => StickyHeadState();
}

class StickyHeadState extends State<StickyHead> {
  String title;
  //列表顶部位置(相对于屏幕)
  double top=0;

  double offsetY=0;

  //StickyHead高度
  static double heightOfSticky=30;
  //当前Section索引
  static int currentIndex = 0;
  //当前字母
  static String currentCharacter='A';

  bool isStickySectionMove() {
    int lastHiddenSectionIndex = 0;
    int topShowSectionIndex = 0;
    double newOffsetY=0;
    GlobalKey key;

    //查询屏幕上方被遮住的第一个Section
    int startIndex = (currentIndex+5) < widget.sections.length ? currentIndex+5 :widget.sections.length-1;
    for(var i=startIndex; i>=0; i--){
      key = widget.sections[i].key;
      if(key.currentContext == null)
        continue;

      double y = key.y();
      if(y <= top) {
        lastHiddenSectionIndex = i;
        break;
      }
    }

    topShowSectionIndex = lastHiddenSectionIndex+1;
    key = widget.sections[topShowSectionIndex].key;
    //如果下一个Section不在屏幕中，则取屏幕上方被遮住的第一个Section
    if (key.currentContext==null){
      offsetY=0;
    }else {
      //如果下一个Section在屏幕中，且滑动到Sticky Section高度内
      //下一个Section将Sticky Section顶起
      double y = key.y();
      if ( y < top + heightOfSticky) {
        newOffsetY = top + heightOfSticky - y;
      }
    }

    if (lastHiddenSectionIndex != currentIndex || newOffsetY != offsetY) {
      currentIndex = lastHiddenSectionIndex;
      currentCharacter = widget.sections[currentIndex].letter;
      offsetY = newOffsetY;
      return true;
    }

    return false;
  }

  @override
  Widget build(BuildContext context) {
    List<Section> datas = widget.sections;

    if(currentIndex<0 || currentIndex>=datas.length)
      return Container();

    Section section = datas[currentIndex];
    String content;
    if(section.isLetter)
      content = section.letter;
    else
      content = "${currentCharacter}   teacher:${section.tname}   class:${section.cname}";
    return Positioned(
      top: -offsetY,
      child: Container(
        width: MediaQuery.of(context).size.width,
        height: heightOfSticky,
        child: Padding(
          padding: EdgeInsets.only(left: 10,top: 2,bottom: 2),
          child: Text(content),
        ),
        color: Colors.blueAccent,
        alignment: Alignment.centerLeft,
      ),
    );
  }
}

extension StikcyHeadKey on GlobalKey<StickyHeadState>{
  void refreshByScroll() {
    if(this.currentState.isStickySectionMove()) {
      this.currentState.setState(() {});
    }
  }

  void refresh() {
    this.currentState.setState(() {});
  }

  void setTop(double value) {
    this.currentState.top = value;
  }

}
